<template>
  <div>
    <!-- 安全级别区 -->
    <el-card class="safety">
      <el-progress
        type="circle"
        :percentage="percentage"
        :color="colors"
      ></el-progress>
      <span
        ><i :class="colorLevel">{{ titleLevel }}</i></span
      >
      <span v-if="percentage < 100"
        >为了更好的保障您的账号安全，请您继续完善账号信息</span
      >
    </el-card>

    <!-- 账号设置区 -->
    <el-card class="information">
      <span class="txt">账号设置</span>
      <el-form :model="userInfoForm" label-width="80px" label-position="left">
        <el-form-item label="账号" label-width="120px">
          <div>
            <span class="title">
              {{
                userInfoForm.userName
                ? userInfoForm.userName
                : '存在风险，请设置账号'
              }}
            </span>
            <span class="btn">
              <el-button type="primary" @click="openUpdateNameDialog">
                {{ userInfoForm.userName ? '修改账号' : '设置账号' }}
              </el-button>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="密码" label-width="120px">
          <div>
            <span class="title">
              {{
                userInfoForm.userPassword ? '******' : '存在风险，请设置密码'
              }}
            </span>
            <span class="btn">
              <el-button type="primary" @click="openUpdatePasswordDialog">
                {{ userInfoForm.userPassword ? '修改密码' : '设置密码' }}
              </el-button>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="手机" label-width="120px">
          <div>
            <span class="title">
              {{
                userInfoForm.userTel ? safetyTel : '存在风险，请绑定手机'
              }}
            </span>
            <span class="btn">
              <el-button type="primary" @click="openUpdateTelDialog">
                {{ userInfoForm.userTel ? '修改手机' : '绑定手机' }}
              </el-button>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px">
          <div>
            <span class="title">
              {{
                userInfoForm.userEmail
                ? userInfoForm.userEmail
                : '存在风险，请绑定邮箱'
              }}
            </span>
            <span class="btn">
              <el-button type="primary" @click="openUpdateEmailDialog">
                {{ userInfoForm.userEmail ? '修改邮箱' : '绑定邮箱' }}
              </el-button>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="账号注销">
          <div>
            <span class="btn">
              <el-button type="primary" @click="quit">立即注销</el-button>
            </span>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 更新账号对话框 -->
    <el-dialog
      title="更新账号"
      v-model="updateNameDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="dialogClose(updateUserFormRef)"
      style="text-align: left;"
    >
      <el-form
        :model="updateUserForm"
        :rules="updateUserRules"
        ref="updateUserFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item label="输入新账号" prop="userName">
          <el-input v-model="updateUserForm.userName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateNameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateName(updateUserFormRef)"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <!-- 更新密码对话框 -->
    <el-dialog
      title="更新密码"
      v-model="updatePasswordDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="dialogClose(updateUserFormRef)"
      style="text-align: left;"
    >
      <el-form
        :model="updateUserForm"
        :rules="updateUserRules"
        ref="updateUserFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item label="输入旧密码" prop="userOldPassword">
          <el-input v-model="updateUserForm.userOldPassword"></el-input>
        </el-form-item>
        <el-form-item label="输入新密码" prop="userNewPassword">
          <el-input
            show-password
            v-model="updateUserForm.userNewPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="userCheckPassword">
          <el-input
            show-password
            v-model="updateUserForm.userCheckPassword"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updatePasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePassword()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 更新电话对话框 -->
    <el-dialog
      title="更新电话"
      v-model="updateTelDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="dialogClose(updateUserFormRef)"
      style="text-align: left;"
    >
      <el-form
        :model="updateUserForm"
        :rules="updateUserRules"
        ref="updateUserFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item label="输入新电话" prop="userTel">
          <el-input v-model="updateUserForm.userTel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateTelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateTel(updateUserFormRef)"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <!-- 更新邮箱对话框 -->
    <el-dialog
      title="更新邮箱"
      v-model="updateEmailDialogVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="dialogClose(updateUserFormRef)"
      style="text-align: left;"
    >
      <el-form
        :model="updateUserForm"
        :rules="updateUserRules"
        ref="updateUserFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item label="输入新邮箱" prop="userEmail">
          <el-input v-model="updateUserForm.userEmail"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateEmailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateEmail(updateUserFormRef)"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useStore } from 'vuex';
import { ref, getCurrentInstance, ComponentInternalInstance, reactive, computed } from 'vue';
import { FormRules, ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import store from '@/store';

const storeData = useStore();
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 新账号验证
const checkUsername = (_: any, value: any, callback: any) => {
  let usernameReg = /^[\u0391-\uFFE5a-zA-Z0-9]{3,12}$/;
  if (!value) {
    return callback(new Error('请输入账号'));
  }
  setTimeout(() => {
    if (usernameReg.test(value)) {
      callback();
    } else {
      callback(new Error('长度在 3 到 12 个字符'));
    }
  }, 100);
};
// 新电话号码验证
const checkPhone = (_: any, value: any, callback: any) => {
  const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
  if (value === '') {
    return callback(new Error('电话号码不能为空'));
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error('请输入数字值'));
    } else {
      if (phoneReg.test(value)) {
        callback();
      } else {
        callback(new Error('电话号码格式不正确'));
      }
    }
  }, 100);
};
// 新密码验证
const checkPassword = (_: any, value: any, callback: any) => {
  let passwordReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,16}$/;
  if (!value) {
    return callback(new Error('请输入密码'));
  }
  setTimeout(() => {
    if (passwordReg.test(value)) {
      callback();
    } else {
      callback(new Error('密码必须为6~16位数字+字母组合'));
    }
  }, 100);
};
// 再次确认新密码验证
const checkPassword2 = (_: any, value: any, callback: any) => {
  if (!updateUserForm.userNewPassword)
    callback(new Error('请先输入新密码'));
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== updateUserForm.userNewPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};
// 新邮箱验证
const checkEmail = (_: any, value: any, callback: any) => {
  const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  if (!value) {
    callback(new Error('邮箱不能为空'));
    // return callback(new Error('邮箱不能为空'));
  }
  setTimeout(() => {
    if (emailReg.test(value)) {
      callback();
    } else {
      callback(new Error('请输入正确的邮箱格式'));
    }
  }, 100);
};
// 安全校验各阶段显示
const colors = ref([
  { color: '#f56c6c', percentage: 75 },
  { color: '#e6a23c', percentage: 100 },
  { color: '#1989fa', percentage: 100 },
]);
// 更新用户表单
interface UpdateUserForm {
  userName: String
  userOldPassword: String
  userNewPassword: String
  userCheckPassword: String
  userTel: String
  userEmail: String
}
const updateUserForm = reactive<UpdateUserForm>({
  userName: '',
  userOldPassword: '',
  userNewPassword: '',
  userCheckPassword: '',
  userTel: '',
  userEmail: '',
});
// 新用户信息表单验证
const updateUserRules = reactive<FormRules<typeof updateUserForm>>({
  userName: [{ validator: checkUsername }],
  userOldPassword: [{ validator: checkPassword }],
  userNewPassword: [{ validator: checkPassword }],
  userCheckPassword: [{ validator: checkPassword2 }],
  userTel: [{ validator: checkPhone }],
  userEmail: [{ validator: checkEmail }],
});
// 更新账号对话框的显示与隐藏
const updateNameDialogVisible = ref(false);
// 更新密码对话框的显示与隐藏
const updatePasswordDialogVisible = ref(false);
// 更新手机对话框的显示与隐藏
const updateTelDialogVisible = ref(false);
// 更新邮箱对话框的显示与隐藏
const updateEmailDialogVisible = ref(false);
const updateUserFormRef = ref<FormInstance>();

// 获取用户信息
interface UserInfoForm {
  userId: Number
  userName: String
  userPassword: String
  userTel: String
  userEmail: String
}
const userInfoForm = computed<UserInfoForm>(() => {
  return storeData.state.userInf.userInfo;
});
// 安全颜色级别
const colorLevel = computed(() => {
  return percentage.value < 75
    ? 'low'
    : percentage.value < 100
      ? 'middle'
      : 'heigh';
});
// 安全校验进度条
const percentage = computed(() => {
  let score = 0;
  if (userInfoForm.value.userName) score += 25;
  if (userInfoForm.value.userPassword) score += 25;
  if (userInfoForm.value.userTel) score += 25;
  if (userInfoForm.value.userEmail) score += 25;
  return score;
});
// 安全字体级别
const titleLevel = computed(() => {
  return percentage.value < 75
    ? '高风险'
    : percentage.value < 100
      ? '低风险'
      : '安全';
});
// 安全电话显示
const safetyTel = computed(() => {
  let reg = /^(\d{3})\d{4}(\d{4})$/;
  return userInfoForm.value.userTel.replace(reg, '$1****$2');
});

// 点击按钮后退出
function quit() {
  ElMessageBox.confirm('此操作将注销账号(即退出登录), 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      proxy.$request.account.logout().then(() => {
        // 清除token
        proxy.$storage.clearAll();
        // 跳转到登录页面
        proxy.$router.replace('/login');
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
      });
    });
};
// 更新用户信息
function updateUserInfo(data: any, formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    data.userId = userInfoForm.value.userId;
    proxy.$request.userInf.updateUserInf(data).then((res: any) => {
      ElMessage.success(res.msg);
      store.dispatch('userInf/getUserInfo', { data: userInfoForm.value.userId })
      proxy.$request.userInf
        .getUserInf({ userId: userInfoForm.value.userId })
        .then((resp: any) => {
          proxy.$request.account.login(resp.data).then((resp1: any) => {
            proxy.$storage.setItem('userInfo', { ...resp1.data });
          });
        });
    });
    formEl.resetFields();
    updateNameDialogVisible.value = false;
    updateTelDialogVisible.value = false;
    updateEmailDialogVisible.value = false;
  });
};
// 关闭对话框后移除表单验证
function dialogClose(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
};
// 点击按钮显示更新账号对话框
function openUpdateNameDialog() {
  updateNameDialogVisible.value = true;
};
// 点击按钮确认更新账号
function updateName(formEl: FormInstance | undefined) {
  updateUserInfo({
    userName: updateUserForm.userName,
  }, formEl);
};
// 点击按钮显示更新密码对话框
function openUpdatePasswordDialog() {
  updatePasswordDialogVisible.value = true;
};
// 点击按钮确认更新密码
function updatePassword() {
  proxy.$request.account
    .updatePassword({
      userId: userInfoForm.value.userId,
      userOldPassword: updateUserForm.userOldPassword,
      userNewPassword: updateUserForm.userNewPassword,
    })
    .then((res: any) => {
      ElMessage.success(res.msg);
      updatePasswordDialogVisible.value = false;
    });
};
// 点击按钮显示更新电话对话框
function openUpdateTelDialog() {
  updateTelDialogVisible.value = true;
};
// 点击按钮确认更新电话
function updateTel(formEl: FormInstance | undefined) {
  updateUserInfo({
    userTel: updateUserForm.userTel,
  }, formEl);
};
// 点击按钮显示更新邮箱对话框
function openUpdateEmailDialog() {
  updateEmailDialogVisible.value = true;
};
// 点击按钮确认更新邮箱
function updateEmail(formEl: FormInstance | undefined) {
  updateUserInfo({
    userEmail: updateUserForm.userEmail,
  }, formEl);
};
</script>

<style lang="less" scoped>
.safety {
  text-align: center;

  span:nth-child(2) {
    display: block;
    margin: 5px 0;

    i {
      display: inline-block;
      color: #fff;
      background-color: red;
      height: 20px;
      line-height: 20px;
      width: 52px;
      font-size: 12px;
      border-radius: 10px;
    }
    .low {
      background-color: #f56c6c;
    }
    .middle {
      background-color: #e6a23c;
    }
    .heigh {
      background-color: #67c23a;
    }
  }

  span:nth-child(3) {
    display: block;
    font-size: 14px;
  }
}

.information {
  /deep/ .el-card__body {
    padding: 0;
  }

  margin-top: 20px;

  .txt {
    display: block;
    padding: 0 20px;
    font-size: 18px;
    font-weight: 600;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #eee;
    text-align: left;
  }
  .el-form {
    /deep/ .el-form-item__label {
      font-size: 16px;
      margin-left: 50px;
      text-align-last: justify;
    }
    /deep/ .el-form-item__content {
      height: 60px;
      width: 100%;
    }
    /deep/ .el-form-item__label{
      width: 120px;
      letter-spacing: 32px;
    }
    .el-form-item {
      margin-top: 25px;
      border-bottom: 1px solid #eee;
      div {
        width: 100%;
        position: absolute;
        margin-bottom: 25px;
        font-size: 16px;
        .title {
          float: left;
          margin-left: 20px;
        }
        .btn{
          float: right;
          margin-right: 40px;
        }
      }
    }

    /deep/ .el-form-item:nth-child(5) {
      border-bottom: none;
      .el-form-item__label{
        letter-spacing: 0;
      }
    }
  }
}
.dialog-footer{
    display: flex;
    justify-content: end;
    width: 100%;
    margin-top: 20px;
  }
</style>
